package db

import (
	"context"

	"github.com/neo4j/neo4j-go-driver/v5/neo4j"
)

type UserBelongsToRole struct {
	_Relationship_ `mapstructure:",squash"`
}

const createUserBelongsToRole = `
// name CreateRole :one
MATCH (u:User)
WHERE elementId(u) = $uid
MATCH (r:Role)
WHERE elementId(r) = $rid
CREATE (u)-[rel:BELONGS_TO]->(r)
RETURN rel
`

type CreateUserBelongsToRoleParam struct {
	UserID string `map:"uid"` // string
	RoleID string `map:"rid"` // string
}

func (dao *DAO) CreateUserBelongsToRole(ctx context.Context, arg CreateUserBelongsToRoleParam) (UserBelongsToRole, error) {
	var i UserBelongsToRole
	argMap, err := NewParamConverter(&arg).AsMap()
	if err != nil {
		return i, err
	}
	_, err = dao.db.ExecTx(ctx, func(tx NeoTransaction) error {
		result, err := tx.Run(ctx, createUserBelongsToRole, argMap)
		if err != nil {
			return err
		}
		err = NewRelationshipLoader(&i).LoadT(ctx, result, "rel")
		if err != nil {
			return err
		}
		dao.db.slog.Infof("i=>%+v", i)
		return nil
	}, neo4j.ExecuteQueryWithDatabase(dao.dbName))

	return i, err
}
